import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';

class TextFieldDemo extends StatefulWidget {
  const TextFieldDemo({Key? key}) : super(key: key);

  @override
  State<TextFieldDemo> createState() => _TextFieldDemoState();
}

class _TextFieldDemoState extends State<TextFieldDemo>
    with WidgetsBindingObserver {
  FocusNode _focusNode = FocusNode();
  OverlayEntry? _overlayEntry;

  // The controller for the text field
  final TextEditingController _controller = TextEditingController();

  // This function is triggered when the clear buttion is pressed
  void _clearTextField() {
    // Clear everything in the text field
    _controller.clear();
    // Call setState to update the UI
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      print('focus:${_focusNode.hasFocus}');
      if (_focusNode.hasFocus) {
        _showOverlay(context);
      } else {
        _removeOverlay();
      }
    });
  }

  @override
  void dispose() {
    print('dispose');
    _focusNode.unfocus();
    _removeOverlay();
    _focusNode.requestFocus();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Kindacode.com'),
        ),
        body: KeyboardVisibilityBuilder(
          builder: (p0, isKeyboardVisible) {
            // if (isKeyboardVisible) {
            //   _showOverlay(context);
            // } else {
            //   _removeOverlay();
            // }
            return KeyboardDismissOnTap(
              child: Column(
                children: [
                  Container(
                    width: 300,
                    height: 50,
                    color: Colors.red,
                  ),
                  TextField(
                    controller: _controller,
                    onChanged: (value) {
                      // Call setState to update the UI
                      setState(() {});
                    },
                    focusNode: _focusNode,
                    decoration: InputDecoration(
                      labelText: 'Search',
                      border: const OutlineInputBorder(),
                      prefixIcon: const Icon(Icons.search),
                      suffixIcon: _controller.text.isEmpty
                          ? null // Show nothing if the text field is empty
                          : IconButton(
                              icon: const Icon(Icons.clear),
                              onPressed: _clearTextField,
                            ), // Show the clear button if the text field has something
                    ),
                  ),
                ],
              ),
            );
          },
        ));
  }

  void _showOverlay(BuildContext context) {
    if (_overlayEntry != null) return;
    OverlayState? overlayState = Overlay.of(context);
    _overlayEntry = OverlayEntry(builder: (ctx) {
      return Positioned(
        left: 0,
        right: 0,
        bottom: MediaQuery.of(ctx).viewInsets.bottom,
        child: Container(
          color: Colors.grey.shade200,
          child: Row(
            children: [
              TextButton(
                  onPressed: () {
                    print('cancel');
                  },
                  child: Text('取消')),
              TextButton(
                  onPressed: () {
                    print('ensure');
                  },
                  child: Text('确定')),
            ],
          ),
        ),
      );
    });
    overlayState?.insert(_overlayEntry!);
  }

  void _removeOverlay() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }
}
